﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Xml.Serialization;
using System.IO;

using Revis.VClinicNet.Core.Domain.Credentials;

namespace Revis.VClinicNet.UI.Internal.Mvc.Infrastructure
{
    public interface IMenu
    {
        IEnumerable<IMenuItem> For(WorkerUserRole role);
    }

    public interface IMenuItem
    {
        string Value { get; }
        string Url { get; }
    }

    [XmlRoot("menus")]
    public class XmlMenu : IMenu
    {
        [XmlElement("menu")]
        public List<XmlRoleMenu> RoleMenus { get; set; }

        public XmlMenu()
        {
            RoleMenus = new List<XmlRoleMenu>();
        }

        public IEnumerable<IMenuItem> For(WorkerUserRole role)
        {
            XmlRoleMenu roleMenu = RoleMenus
                .Where(m => m.Role == role)
                .Single();
            return roleMenu.Items;
        }

        public static IMenu LoadFrom(string filePath)
        {
            XmlSerializer serializer = new XmlSerializer(typeof(XmlMenu));
            XmlMenu menu = null;
            using (StreamReader reader = new StreamReader(filePath)) {
                menu = (XmlMenu)serializer.Deserialize(reader);
                reader.Close();
            }
            return menu;
        }
    }

    public class XmlRoleMenu
    {
        [XmlElement("item")]
        public List<XmlMenuItem> MenuItems { get; set; }

        [XmlAttribute("for")]
        public WorkerUserRole Role { get; set; }

        public XmlRoleMenu()
        {
            MenuItems = new List<XmlMenuItem>();
        }

        public IEnumerable<IMenuItem> Items
        {
            get { return MenuItems.ConvertAll(item => (IMenuItem)item); }
        }
    }

    public class XmlMenuItem : IMenuItem
    {
        [XmlAttribute("value")]
        public string Value { get; set; }
        [XmlAttribute("url")]
        public string Url { get; set; }
    }

    public class UserMenuViewModel
    {
        public IEnumerable<IMenuItem> MenuItems { get; protected set; }

        public UserMenuViewModel()
        {
            MenuItems = new List<IMenuItem>();
        }

        public UserMenuViewModel(IEnumerable<IMenuItem> menuItems)
        {
            MenuItems = menuItems;
        }
    }
}
